<template>
  <div class="heavy-component-container" :class="{ 'dark-mode': isDarkMode }">
    <h3>重型演示组件</h3>
    <div class="component-info">
      <p>这是一个模块化的重型组件，包含大量数据和复杂渲染功能</p>
      <p>通过组件拆分和异步加载，提高了可维护性和性能</p>
    </div>
    
    <!-- 主题切换组件 -->
    <ThemeSwitcher 
      v-model="isDarkMode" 
      @theme-change="handleThemeChange"
    />
    
    <!-- 数据导入组件 -->
    <DataImport 
      @data-imported="handleDataImported" 
      @import-status-change="handleImportStatusChange"
    />
    
    <!-- 搜索和基础筛选组件 -->
    <SearchFilter 
      v-model:searchQuery="searchQuery"
      v-model:statusFilter="statusFilter"
      v-model:valueFilter="valueFilter"
      v-model:sortField="sortField"
      v-model:sortOrder="sortOrder"
      @filters-change="handleFiltersChange"
      @sort-change="handleSortChange"
      @reset="handleResetFilters"
    />
    
    <!-- 高级筛选组件 -->
    <AdvancedFilter 
      v-model:filters="advancedFilters"
      @filters-change="handleAdvancedFiltersChange"
    />
    
    <!-- 数据可视化组件 -->
    <DataVisualization 
      v-model:chartType="chartType"
      :chartData="chartData"
      v-model:colorScheme="colorScheme"
      v-model:customColor="customColor"
      @chart-type-change="handleChartTypeChange"
      @color-scheme-change="handleColorSchemeChange"
      @refresh-data="regenerateChartData"
    >
      <template #default="{ chartType, chartData }">
        <div v-if="chartType === 'bar'" class="bar-chart">
          <div 
            v-for="(value, index) in chartData" 
            :key="index" 
            class="bar"
            :style="{ 
              height: `${Math.min(value * 0.3, 200)}px`, 
              backgroundColor: getBarColor(value) 
            }"
          >
            <span v-if="showLabels" class="bar-label">{{ value }}</span>
          </div>
        </div>
        <div v-else-if="chartType === 'line'" class="line-chart">
          <!-- 简化的折线图实现 -->
          <div class="line-container">
            <div 
              v-for="(value, index) in chartData" 
              :key="index" 
              class="line-point"
              :style="{ 
                bottom: `${value * 0.3}px`, 
                left: `${index * (100 / (chartData.length - 1))}%` 
              }"
            >
              <span v-if="showLabels" class="point-label">{{ value }}</span>
            </div>
          </div>
        </div>
        <div v-else-if="chartType === 'pie'" class="pie-chart">
          <!-- 简化的饼图实现 -->
          <div class="pie-container">
            <div 
              v-for="(value, index) in chartData" 
              :key="index" 
              class="pie-segment"
              :style="{ backgroundColor: getPieColor(index) }"
            >
              <span v-if="showLabels" class="segment-label">{{ value }}</span>
            </div>
          </div>
        </div>
        <div v-else class="chart-placeholder">
          <span>图表类型: {{ chartType }}</span>
        </div>
      </template>
    </DataVisualization>
    
    <!-- 数据表格区域 -->
    <div class="data-table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>名称</th>
            <th>数值</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in paginatedData" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.value }}</td>
            <td>
              <span class="status-badge" :class="`status-${item.status}`">
                {{ getStatusLabel(item.status) }}</span>
            </td>
            <td>
              <button @click="viewItemDetails(item)" class="action-btn view-btn">查看</button>
              <button @click="toggleSelectItem(item.id)" class="action-btn select-btn">
                {{ isSelected(item.id) ? '取消' : '选择' }}</button>
            </td>
          </tr>
          <tr v-if="paginatedData.length === 0">
            <td colspan="5" class="no-data">暂无数据</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页组件 -->
      <Pagination 
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :totalItems="filteredData.length"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      />
    </div>
    
    <!-- 底部操作区域 -->
    <div class="bottom-actions">
      <div class="selection-info">
        <span>已选择 {{ selectedItems.length }} 项</span>
        <button 
          @click="clearSelection" 
          class="clear-selection-btn"
          :disabled="selectedItems.length === 0"
        >
          清除选择
        </button>
      </div>
      <div class="cache-actions">
        <button @click="saveSettings" class="save-settings-btn">保存设置</button>
        <button @click="clearCache" class="clear-cache-btn">清除缓存</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 导入子组件
import ThemeSwitcher from './ThemeSwitcher.vue'
import DataImport from './DataImport.vue'
import SearchFilter from './SearchFilter.vue'
import AdvancedFilter from './AdvancedFilter.vue'
import DataVisualization from './DataVisualization.vue'
import Pagination from './Pagination.vue'

// 响应式状态
const isDarkMode = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const valueFilter = ref(100)
const sortField = ref('id')
const sortOrder = ref('asc')
const advancedFilters = ref([])
const chartType = ref('bar')
const colorScheme = ref('default')
const customColor = ref('#4CAF50')
const showLabels = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedItems = ref([])
const tableData = ref([])
const chartData = ref([])

// 组件挂载时初始化数据
onMounted(() => {
  initializeData()
  loadSettings()
})

// 初始化数据
const initializeData = () => {
  // 生成示例表格数据
  tableData.value = Array.from({ length: 100 }, (_, i) => ({
    id: i + 1,
    name: `项目 ${i + 1}`,
    value: Math.floor(Math.random() * 900) + 100,
    status: ['active', 'pending', 'completed', 'error'][Math.floor(Math.random() * 4)]
  }))
  
  // 生成示例图表数据
  regenerateChartData()
}

// 重新生成图表数据
const regenerateChartData = () => {
  chartData.value = Array.from({ length: 10 }, () => Math.floor(Math.random() * 600) + 100)
}

// 根据筛选条件过滤数据
const filteredData = computed(() => {
  let data = [...tableData.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    data = data.filter(item => 
      item.name.toLowerCase().includes(query) || 
      item.id.toString().includes(query)
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    data = data.filter(item => item.status === statusFilter.value)
  }
  
  // 数值过滤
  data = data.filter(item => item.value >= valueFilter.value)
  
  // 高级过滤
  advancedFilters.value.forEach(filter => {
    data = data.filter(item => {
      const itemValue = item[filter.field]
      switch (filter.operator) {
        case 'equals':
          return itemValue === filter.value1
        case 'greater':
          return itemValue > filter.value1
        case 'less':
          return itemValue < filter.value1
        case 'between':
          return itemValue >= filter.value1 && itemValue <= filter.value2
        default:
          return true
      }
    })
  })
  
  // 排序
  data.sort((a, b) => {
    const aValue = a[sortField.value]
    const bValue = b[sortField.value]
    return sortOrder.value === 'asc' ? aValue - bValue : bValue - aValue
  })
  
  return data
})

// 分页数据
const paginatedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredData.value.slice(startIndex, endIndex)
})

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    active: '活跃',
    pending: '待处理',
    completed: '已完成',
    error: '错误'
  }
  return statusMap[status] || status
}

// 获取柱状图颜色
const getBarColor = (value) => {
  if (colorScheme.value === 'custom') return customColor.value
  
  switch (colorScheme.value) {
    case 'pastel':
      return value < 300 ? '#ffcccc' : value < 600 ? '#ffffcc' : '#ccffcc'
    case 'vibrant':
      return value < 300 ? '#ff5252' : value < 600 ? '#ffeb3b' : '#4caf50'
    case 'monochrome':
      return value < 300 ? '#9e9e9e' : value < 600 ? '#616161' : '#212121'
    default:
      return value < 300 ? '#ff9800' : value < 600 ? '#2196f3' : '#4caf50'
  }
}

// 获取饼图颜色
const getPieColor = (index) => {
  if (colorScheme.value === 'custom') {
    const hue = (parseInt(customColor.value.slice(1), 16) + index * 40) % 360
    return `hsl(${hue}, 70%, 60%)`
  }
  
  const colorMaps = {
    pastel: ['#ffcccc', '#ccffcc', '#ccccff', '#ffffcc', '#ffccff', '#ccffff'],
    vibrant: ['#ff5252', '#4caf50', '#2196f3', '#ffeb3b', '#9c27b0', '#00bcd4'],
    monochrome: ['#9e9e9e', '#757575', '#616161', '#424242', '#212121', '#000000'],
    default: ['#ff9800', '#4caf50', '#2196f3', '#f44336', '#9c27b0', '#00bcd4']
  }
  
  const colors = colorMaps[colorScheme.value] || colorMaps.default
  return colors[index % colors.length]
}

// 检查项目是否被选中
const isSelected = (id) => {
  return selectedItems.value.includes(id)
}

// 切换选择状态
const toggleSelectItem = (id) => {
  const index = selectedItems.value.indexOf(id)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(id)
  }
}

// 清除选择
const clearSelection = () => {
  selectedItems.value = []
}

// 查看项目详情
const viewItemDetails = (item) => {
  console.log('查看项目详情:', item)
  // 可以实现详情弹窗或其他逻辑
}

// 处理主题变化
const handleThemeChange = (darkMode) => {
  isDarkMode.value = darkMode
  saveSettings()
}

// 处理数据导入
const handleDataImported = (data) => {
  console.log('导入的数据:', data)
  // 处理导入的数据，可以合并到现有数据中
}

// 处理导入状态变化
const handleImportStatusChange = (statusInfo) => {
  console.log('导入状态:', statusInfo)
}

// 处理筛选条件变化
const handleFiltersChange = (filters) => {
  console.log('筛选条件变化:', filters)
  currentPage.value = 1 // 筛选条件变化时重置到第一页
}

// 处理高级筛选条件变化
const handleAdvancedFiltersChange = (filters) => {
  console.log('高级筛选条件变化:', filters)
  currentPage.value = 1 // 筛选条件变化时重置到第一页
}

// 处理排序变化
const handleSortChange = (sortInfo) => {
  console.log('排序变化:', sortInfo)
}

// 重置筛选条件
const handleResetFilters = () => {
  console.log('重置筛选条件')
  currentPage.value = 1
}

// 处理图表类型变化
const handleChartTypeChange = (type) => {
  console.log('图表类型变化:', type)
  saveSettings()
}

// 处理颜色方案变化
const handleColorSchemeChange = (colorInfo) => {
  console.log('颜色方案变化:', colorInfo)
  saveSettings()
}

// 处理页码变化
const handlePageChange = (page) => {
  console.log('页码变化:', page)
}

// 处理页面大小变化
const handlePageSizeChange = (size) => {
  console.log('页面大小变化:', size)
  saveSettings()
}

// 保存设置到localStorage
const saveSettings = () => {
  try {
    const settings = {
      sortField: sortField.value,
      sortOrder: sortOrder.value,
      statusFilter: statusFilter.value,
      valueFilter: valueFilter.value,
      pageSize: pageSize.value,
      isDarkMode: isDarkMode.value,
      chartType: chartType.value,
      colorScheme: colorScheme.value,
      customColor: customColor.value,
      advancedFilters: advancedFilters.value
    }
    localStorage.setItem('heavyComponentSettings', JSON.stringify(settings))
    console.log('设置已保存')
  } catch (error) {
    console.error('保存设置失败:', error)
  }
}

// 从localStorage加载设置
const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('heavyComponentSettings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      if (settings.sortField) sortField.value = settings.sortField
      if (settings.sortOrder) sortOrder.value = settings.sortOrder
      if (settings.statusFilter) statusFilter.value = settings.statusFilter
      if (settings.valueFilter) valueFilter.value = settings.valueFilter
      if (settings.pageSize) pageSize.value = settings.pageSize
      if (settings.isDarkMode !== undefined) isDarkMode.value = settings.isDarkMode
      if (settings.chartType) chartType.value = settings.chartType
      if (settings.colorScheme) colorScheme.value = settings.colorScheme
      if (settings.customColor) customColor.value = settings.customColor
      if (settings.advancedFilters) advancedFilters.value = settings.advancedFilters
      console.log('设置已加载')
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 清除缓存
const clearCache = () => {
  try {
    localStorage.removeItem('heavyComponentSettings')
    console.log('缓存已清除')
  } catch (error) {
    console.error('清除缓存失败:', error)
  }
}
</script>

<style scoped>
.heavy-component-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s, color 0.3s;
}

h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.component-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #2196F3;
}

.component-info p {
  margin: 5px 0;
  color: #666;
}

.data-table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.status-pending {
  background-color: #fff8e1;
  color: #f57c00;
}

.status-completed {
  background-color: #e3f2fd;
  color: #1565c0;
}

.status-error {
  background-color: #ffebee;
  color: #c62828;
}

.action-btn {
  padding: 6px 12px;
  margin-right: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.view-btn {
  background-color: #2196F3;
  color: white;
}

.view-btn:hover {
  background-color: #1976D2;
}

.select-btn {
  background-color: #4CAF50;
  color: white;
}

.select-btn:hover {
  background-color: #45a049;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 20px;
}

.bottom-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ddd;
}

.selection-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.clear-selection-btn,
.save-settings-btn,
.clear-cache-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.clear-selection-btn {
  background-color: #f44336;
  color: white;
}

.clear-selection-btn:hover:not(:disabled) {
  background-color: #d32f2f;
}

.clear-selection-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.save-settings-btn {
  background-color: #4CAF50;
  color: white;
  margin-right: 10px;
}

.save-settings-btn:hover {
  background-color: #45a049;
}

.clear-cache-btn {
  background-color: #ff9800;
  color: white;
}

.clear-cache-btn:hover {
  background-color: #f57c00;
}

.cache-actions {
  display: flex;
  gap: 10px;
}

/* 图表样式 */
.bar-chart {
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  height: 100%;
  padding: 20px 0;
}

.bar {
  width: 50px;
  background-color: #2196F3;
  border-radius: 4px 4px 0 0;
  display: flex;
  justify-content: center;
  position: relative;
  transition: height 0.5s ease;
}

.bar-label {
  position: absolute;
  bottom: -20px;
  font-size: 12px;
  color: #666;
}

.line-chart {
  height: 100%;
  position: relative;
}

.line-container {
  position: relative;
  height: 100%;
  width: 100%;
}

.line-point {
  position: absolute;
  width: 12px;
  height: 12px;
  background-color: #f44336;
  border-radius: 50%;
  transform: translate(-50%, 50%);
}

.point-label {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #666;
}

.pie-chart {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pie-container {
  width: 200px;
  height: 200px;
  position: relative;
  border-radius: 50%;
  overflow: hidden;
}

.pie-segment {
  position: absolute;
  width: 100%;
  height: 100%;
  clip-path: polygon(50% 50%, 50% 0%, 100% 0%, 100% 30%, 50% 50%);
}

.segment-label {
  position: absolute;
  top: 50%;
  left: 70%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
}

.chart-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 18px;
}

/* 深色模式下的样式 */
.dark-mode {
  background-color: #1e1e1e;
  color: #ffffff;
}

.dark-mode h3 {
  color: #ffffff;
}

.dark-mode .component-info {
  background-color: #2d2d2d;
  border-left-color: #64b5f6;
}

.dark-mode .component-info p {
  color: #cccccc;
}

.dark-mode .data-table {
  background-color: #2d2d2d;
}

.dark-mode .data-table th {
  background-color: #3d3d3d;
  color: #ffffff;
}

.dark-mode .data-table th,
.dark-mode .data-table td {
  border-bottom-color: #555;
  color: #ffffff;
}

.dark-mode .bottom-actions {
  border-top-color: #555;
}

.dark-mode .bar-label,
.dark-mode .point-label,
.dark-mode .segment-label {
  color: #cccccc;
}

.dark-mode .chart-placeholder {
  color: #999999;
}

.dark-mode .status-active {
  background-color: #1b5e20;
  color: #81c784;
}

.dark-mode .status-pending {
  background-color: #e65100;
  color: #ffcc80;
}

.dark-mode .status-completed {
  background-color: #1565c0;
  color: #90caf9;
}

.dark-mode .status-error {
  background-color: #b71c1c;
  color: #ffcdd2;
}
</style>